package com.maccuoi.letsgo;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.maccuoi.letsgo.AppMessageBox;

public class MainActivity extends Activity {

	SharedPreferences sharedPreferences;

	// Elements
	public TextView outputText;
	public EditText txtPhone;
	Button btnSubmit;

	// Map attrib
	private GoogleMap mMap;
	private LatLng myLocation, myDestination;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Get elements

		sharedPreferences = getSharedPreferences(
				getResources().getString(R.string.pref_key_app),
				Context.MODE_PRIVATE);
		if (sharedPreferences.contains("phone")) {
			// Logedin show main activity

			setContentView(R.layout.activity_map);

			mMap = ((MapFragment) getFragmentManager().findFragmentById(
					R.id.map)).getMap();

			// Add this line
			mMap.setMyLocationEnabled(true);
			mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
				
				@Override
				public void onMyLocationChange(Location location) {
//					LatLng latlong = new LatLng(location.getLatitude(),
//			                location.getLongitude());
//					
//					mMap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
//					mMap.animateCamera(CameraUpdateFactory.zoomBy(8));
					//AppMessageBox.alert(MainActivity.this, "Info", "Your location changed!");
					//Toast.makeText(MainActivity.this, location.getLatitude() + ":" + location.getLongitude() , 5);
				}
			});
			mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {

				@Override
				public boolean onMyLocationButtonClick() {
					Location myLocation = mMap.getMyLocation();
					
					if (myLocation != null) {
						double dLatitude = myLocation.getLatitude();
						double dLongitude = myLocation.getLongitude();
						Log.i("APPLICATION", " : " + dLatitude);
						Log.i("APPLICATION", " : " + dLongitude);
						mMap.addMarker(new MarkerOptions()
								.position(new LatLng(dLatitude, dLongitude))
								.title("My Location")
								.icon(BitmapDescriptorFactory
										.fromResource(R.drawable.marker16)));
						mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
								new LatLng(dLatitude, dLongitude), 17));

					} else {
						AppMessageBox.alert(MainActivity.this, "Info", "Unable to fetch the current location");
					}
					return true;
				}

			});

		} else {
			AppMessageBox.alert(MainActivity.this,
					getResources().getString(R.string.vi_msg_alert_title),
					"Vui lòng đăng nhập");

			setContentView(R.layout.activity_main);

			txtPhone = (EditText) findViewById(R.id.txtPhone);
			btnSubmit = (Button) findViewById(R.id.btnSubmit);

			btnSubmit.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					if ("".equals(txtPhone.getText().toString())) {
						AppMessageBox.alert(MainActivity.this, getResources()
								.getString(R.string.vi_msg_alert_title),
								"Vui lòng nhập vào số điện thoại");
						return;
					} else {
						new UserRegistryTask(MainActivity.this, txtPhone
								.getText().toString()).execute();
						AppMessageBox.alert(MainActivity.this, getResources()
								.getString(R.string.vi_msg_alert_title),
								"Đang đăng ký");
					}
				}
			});
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			return rootView;
		}
	}

	public void fetchContacts() {

		String phoneNumber = null;
		String email = null;

		Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
		String _ID = ContactsContract.Contacts._ID;
		String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
		String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

		Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
		String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;

		Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
		String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
		String DATA = ContactsContract.CommonDataKinds.Email.DATA;

		StringBuffer output = new StringBuffer();

		ContentResolver contentResolver = getContentResolver();

		Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
				null);
		output.append("");
		// Loop for every contact in the phone
		if (cursor.getCount() > 0) {

			while (cursor.moveToNext()) {

				String contact_id = cursor
						.getString(cursor.getColumnIndex(_ID));
				String name = cursor.getString(cursor
						.getColumnIndex(DISPLAY_NAME));

				int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
						.getColumnIndex(HAS_PHONE_NUMBER)));

				if (hasPhoneNumber > 0) {

					output.append("\n First Name:" + name);

					// Query and loop for every phone number of the contact
					Cursor phoneCursor = contentResolver.query(
							PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
							new String[] { contact_id }, null);

					while (phoneCursor.moveToNext()) {
						phoneNumber = phoneCursor.getString(phoneCursor
								.getColumnIndex(NUMBER));
						output.append("\n Phone number:" + phoneNumber);

					}

					phoneCursor.close();

					// Query and loop for every email of the contact
					Cursor emailCursor = contentResolver.query(
							EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?",
							new String[] { contact_id }, null);

					while (emailCursor.moveToNext()) {

						email = emailCursor.getString(emailCursor
								.getColumnIndex(DATA));

						output.append("\nEmail:" + email);

					}

					emailCursor.close();
				}

				output.append("\n");
			}
		}
		outputText.setText(output);
	}

}
